package com.itheima.edu.info.manager.thread;

import com.itheima.edu.info.manager.domain.Student;
import com.itheima.edu.info.manager.service.StudentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class SocketRunnable implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(SocketRunnable.class);
    Random r = new Random();
    private Socket socket;
    private StudentService service = new StudentService();

    public SocketRunnable(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {

        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String readLine = br.readLine();
            String[] split = readLine.split(",");
            LOGGER.info("接收到客户端连接,本次任务是:" + split[0]);
            //3. 取出0索引位置的元素,进行操作匹配
            switch (split[0]) {
                case "[0]":
                    verifyCode();
                    break;
                case "[1]":
                    addStudent(split);
                    break;
                case "[2]":
                    deleteStudent(split);
                    break;
                case "[3]":
                    updateStudent(split);
                    break;
                case "[4]":
                    findAllStudents();
                    break;
                case "[5]":
                    isExists(split[1]);
                    break;
                case "[6]":
                    Register(split[1], split[2]);
                    break;
                default:
                    System.out.println("服务器正忙...");
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
        //注册
    private void Register(String name, String password) throws IOException {
        boolean addAdminstator = service.addAdminstator(name, password);
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        bw.write(addAdminstator + "");
        bw.flush();
        socket.shutdownOutput();
        socket.close();
    }


    private void verifyCode() throws IOException {
        LOGGER.info("接收到客户端请求，正在发送验证码......");
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        StringBuilder s = new StringBuilder();
        for (char i = 'a'; i <= 'z'; i++) {
            s.append(i);
        }
        for (char i = 'A'; i <= 'Z'; i++) {
            s.append(i);
        }
        for (char i = '0'; i <= '9'; i++) {
            s.append(i);
        }

        StringBuilder verifyCode = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            int index = r.nextInt(s.length());
            char ch = s.charAt(index);
            verifyCode.append(ch);

        }
        LOGGER.info("正在发送的验证码为......"+verifyCode);
        bw.write(verifyCode.toString());
        bw.flush();
        socket.shutdownOutput();
        socket.close();

    }

    private void updateStudent(String[] split) throws IOException {
        LOGGER.info("接收到客户端修改学生信息请求，正在执行......");
        Student stu = new Student(split[1], split[2], split[3], split[4]);
        boolean update = service.updateStudent(split[1], stu);
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        bw.write(update + "");
        bw.flush();
        socket.shutdownOutput();
        socket.close();

    }

    private void deleteStudent(String[] split) throws IOException {
        LOGGER.info("接收到客户端删除学生信息请求，正在执行......");
        boolean delete = service.deleteStudent(split[1]);
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        bw.write(delete + "");
        bw.flush();
        socket.shutdownOutput();
        socket.close();
    }

    private void isExists(String sid) throws IOException {
        LOGGER.info("接收到客户端请求，正在进行id校验......");
        boolean exists = service.isExists(sid);
        //将结果写回客户端
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        bw.write(exists + "");
        bw.flush();
        socket.shutdownOutput();
        socket.close();
    }

    private void findAllStudents() throws IOException {
        LOGGER.info("接收到客户端查询学生信息请求，正在执行......");
        //1. 指挥业务员查询到所有学生信息
        Student[] allStudent = service.findAllStudent();
        ArrayList<Student> students = new ArrayList<>(List.of(allStudent));
        Collections.sort(students);
        ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
        oos.writeObject(students);
        socket.close();
    }

    private void addStudent(String[] split) throws IOException {
        LOGGER.info("接收到客户端添加学生信息请求，正在执行......");
        Student stu = new Student(split[1], split[2], split[3], split[4]);
        boolean res = service.addStudent(stu);
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        bw.write(res + "");
        bw.flush();
        socket.shutdownOutput();
        socket.close();

    }
}
